/**
 *  学习目标：Todos 案例
 */
import React from 'react';
import './styles/base.css';
import './styles/index.css';

class Header extends React.Component {
  state = {
    task: '',
  };
  handleAdd = (e) => {
    this.setState({
      task: e.target.value,
    });
  };
  // 判断回车事件
  handleKeyUp = (e) => {
    // console.log(e);
    if (e.key === 'Enter') {
      // console.log(1);
      if (this.state.task.trim() === '') {
        alert('内容不能为空');
        this.setState({
          task: '',
        });
        return;
      }
      this.props.handleAddList(e.target.value);
      this.setState({
        task: '',
      });
    }
  };
  render() {
    const { task } = this.state;
    return (
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          placeholder="需要做什么"
          autoFocus
          value={task}
          onChange={this.handleAdd}
          onKeyUp={this.handleKeyUp}
        />
      </header>
    );
  }
}

class Main extends React.Component {
  render() {
    //  子组件（类组件）通过 this.props 来接受父组件传来的东西
    const { list, handleUpdateList, handleDeleteById, isAll } = this.props;
    // console.log(list);
    return (
      <section className="main">
        <input
          id="toggle-all"
          className="toggle-all"
          type="checkbox"
          checked={isAll}
        />
        <label htmlFor="toggle-all">全选</label>
        <ul className="todo-list">
          {list.map((item) => {
            return (
              <li className={item.isDone ? 'completed' : ''} key={item.id}>
                <div className="view">
                  <input
                    className="toggle"
                    type="checkbox"
                    checked={item.isDone}
                    onChange={handleUpdateList.bind(this, item.id)}
                  />
                  <label>{item.task}</label>
                  <button
                    className="destroy"
                    onClick={handleDeleteById.bind(this, item.id)}
                  ></button>
                </div>
              </li>
            );
          })}
        </ul>
      </section>
    );
  }
}

class Footer extends React.Component {
  // 剩余(未完成)
  get residue() {
    const residue = this.props.list.filter((item) => item.isDone === false);
    return residue.length;
  }
  render() {
    const { handleClearIsOk } = this.props;
    return (
      <footer className="footer">
        <span className="todo-count">
          <strong>{this.residue}</strong> 剩余
        </span>
        <ul className="filters">
          <li>
            <a className="all selected" href="#/">
              全部
            </a>
          </li>
          <li>
            <a className="active" href="#/active">
              未完成
            </a>
          </li>
          <li>
            <a className="completed" href="#/completed">
              已完成
            </a>
          </li>
        </ul>
        <button className="clear-completed" onClick={handleClearIsOk}>
          清除已完成
        </button>
      </footer>
    );
  }
}
export default class App extends React.Component {
  state = {
    list: [
      {
        task: '吃饭',
        isDone: false,
        id: 1,
      },
      {
        task: '睡觉',
        isDone: true,
        id: 2,
      },
    ],
  };
  // 修改list中的isDone
  handleUpdateList = (id, e) => {
    // 方式一
    // const NewList = this.state.list.map((item) => {
    //   return { ...item, isDone: id === item.id ? !item.isDone : item.isDone };
    // });
    // this.setState({
    //   list: NewList,
    // });

    // 方式二
    // console.log(id, e);
    const index = this.state.list.findIndex((item) => item.id === id);
    // console.log(index);
    const list = [...this.state.list];
    list[index].isDone = e.target.checked;
    this.setState({ list });
  };
  // 删除数据
  handleDeleteById = (id) => {
    // console.log('id', id);
    // 方式一
    // this.setState({
    //   list: this.state.list.filter((item) => {
    //     if (item.id !== id) {
    //       return item;
    //     }
    //   }),
    // });

    // 方式二
    const index = this.state.list.findIndex((item) => item.id === id);
    const list = [...this.state.list];
    list.splice(index, 1);
    this.setState({ list });
  };
  // 添加数据
  handleAddList = (task) => {
    // console.log(task);
    const list = [...this.state.list];
    let id = list.length === 0 ? 1 : list[list.length - 1].id + 1;
    list.push({
      task,
      isDone: false,
      id: id,
    });
    this.setState({ list });
  };
  // 清除已完成
  handleClearIsOk = () => {
    // console.log('被触发');
    this.setState({
      list: this.state.list.filter((item) => item.isDone === false),
    });
  };
  render() {
    // 这里需要注意，使用every时，数组为空的时候，为true，这里需要判断一下
    const isAll = this.state.list.length
      ? this.state.list.every((item) => item.isDone)
      : false;
    // console.log(isAll);
    return (
      <section className="todoapp">
        {/* 头部 */}
        <Header handleAddList={this.handleAddList}></Header>
        {/* 主体 */}
        {/* 父传子 list={this.state.list} 不需要像vue那样先定义 props 在后使用，在react中可以直接使用 */}
        <Main
          list={this.state.list}
          handleUpdateList={this.handleUpdateList}
          handleDeleteById={this.handleDeleteById}
          isAll={isAll}
        ></Main>
        {/* 底部 */}
        <Footer
          list={this.state.list}
          handleClearIsOk={this.handleClearIsOk}
        ></Footer>
      </section>
    );
  }
}
